import { Skeleton } from '@nutui/nutui-react-taro';
import Taro, { useDidShow, useRouter } from '@tarojs/taro';
import { useCallback } from 'react'
import { StorageKey } from '@/constants/storage'
import { RouterUtil, formatAppLoadParams, TabbarUtil } from '@/utils';
import { useShareEvent } from '@/hooks';
import { isEmpty } from 'lodash-es';
import type { AppLoadParamsProps } from '@/interfaces/base';
const Page = () => {

  useShareEvent();

  useDidShow(async () => {
    handleStartParams();

    const token = Taro.getStorageSync(StorageKey.TOKEN);
    // 如果 token 存在，获取当前登录用户信息
    if (token) {
      // const userInfo = await fetchUserInfo();
      // await fetchCompanyInfo();
      // await fetchMenuList();
      // await fetchRoleMenuList(userInfo?.roleType as number);
    }

    // 存在分享参数时，useShareEvent 会自行处理跳转，这里不再重复跳转
    handleNavigate();
  });


  // 处理启动参数
  const handleStartParams = useCallback(() => {
    const options = Taro.getLaunchOptionsSync();
    let optionsQuery = options?.query;
    // 二次扫码参数
    const enterOptionsQuery = Taro.getEnterOptionsSync()?.query ?? {};
    if (!isEmpty(enterOptionsQuery)) {
      optionsQuery = enterOptionsQuery;
    }
    const params: AppLoadParamsProps = formatAppLoadParams(optionsQuery);
    // TODO MOCK
    params.shopId = '208';
    
    // 检查是否存在 shopId 参数
    const hasShopId = !!(params.shopId || optionsQuery?.shopId);
    console.log('检测到 shopId:', hasShopId, params.shopId || optionsQuery?.shopId);
    
    // 存储 shopId 状态，用于控制 tabbar 显示
    Taro.setStorageSync(StorageKey.HAS_SHOP_ID, hasShopId);
    
    if (hasShopId) {
      // 存储 shopId
      Taro.setStorageSync(StorageKey.SHOP_ID, params.shopId || optionsQuery?.shopId);
    }
    
    // 处理跳转路径
    if (params.path) {
      Taro.setStorageSync(
        StorageKey.APP_START_REDIRECT_PATH,
        `/pages/${params.path}/index`,
      );
    } else {
      // 根据是否有 shopId 设置默认跳转路径
      const defaultPath = hasShopId ? '/pages/home/index/index' : '/pages/my/index/index';
      Taro.setStorageSync(StorageKey.APP_START_REDIRECT_PATH, defaultPath);
    }
  }, []);

  // 处理跳转
  const handleNavigate = useCallback(() => {
    const path = Taro.getStorageSync(StorageKey.APP_START_REDIRECT_PATH);
    const hasShopId = Taro.getStorageSync(StorageKey.HAS_SHOP_ID);
    
    // 判断是否是tabbar页面（只有在有 shopId 的情况下才有 tabbar）
    const isTabbarPage = hasShopId && TabbarUtil.isTabbarPage(path);
    
    if (isTabbarPage) {
      RouterUtil.switchTab(path);
    } else {
      RouterUtil.navigateTo(path);
    }
  }, []);

  return <Skeleton title rows={10} animated />;
};

export default Page;
